package com.zjm.zdk.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Iterator;

/**
 * 直接基于非阻塞的写法
 */
public class Server1 {

    private static ArrayList<SocketChannel> channels = new ArrayList<>();

    public static void main(String[] args) throws Exception {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.socket().bind(new InetSocketAddress(8888));
        System.out.println("启动成功");
        while (true) {
            SocketChannel socketChannel1 = serverSocketChannel.accept();
            if (socketChannel1 != null) {
                System.out.println("收到请求，来自：" + socketChannel1.getRemoteAddress());
                socketChannel1.configureBlocking(false);
                channels.add(socketChannel1);
            } else {
                Iterator<SocketChannel> iterator = channels.iterator();
                while (iterator.hasNext()) {
                    SocketChannel ch = iterator.next();
                    try {
                        // 读取客户端请求
                        ByteBuffer reqBuffer = ByteBuffer.allocate(1024);
                        if (ch.read(reqBuffer) == 0) {
                            continue;
                        }
                        while (ch.isOpen() && ch.read(reqBuffer) != -1) {
                            if (reqBuffer.position() > 0) {
                                break;
                            }
                        }
                        if (reqBuffer.position() == 0) {
                            continue;
                        }
                        reqBuffer.flip();
                        byte[] content = new byte[reqBuffer.limit()];
                        reqBuffer.get(content);
                        System.out.println(new String(content));
                        System.out.println("收到数据，来自：" + ch.getRemoteAddress() + "\r\n");

                        // 响应结果200
                        String response = "HTTP/1.1 200 OK\r\n" +
                                "Content-Length: 11\r\n\r\n" +
                                "Hello world";
                        ByteBuffer buffer = ByteBuffer.wrap(response.getBytes());
                        while (buffer.hasRemaining()) {
                            ch.write(buffer);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
